Face Detection
importing the libraries
import cv2
import numpy as np
import matplotlib.pyplot as plt
class FaceDetector():
def __init__(self,faceCascadePath):
self.faceCascade=cv2.CascadeClassifier(faceCascadePath)
def detect(self, image, scaleFactor=1.1,
minNeighbors=5,
minSize=(30,30)):
#function return rectangle coordinates of faces for given image
rects=self.faceCascade.detectMultiScale(image,
scaleFactor=scaleFactor,
minNeighbors=minNeighbors,
minSize=minSize)
return rects
path = "haarcascade_frontalface_default.xml"
face_detection = FaceDetector(path)
# Read the input image
img = cv2.imread('people1.jpg')
def show_image(image):
plt.figure(figsize=(18,15))
#Before showing image, bgr color order transformed to rgb order
plt.imshow(cv2.cvtColor(image, cv2.COLOR_BGR2RGB))
plt.xticks([])
plt.yticks([])
plt.show()
show_image(img)
def detect_face(image, scaleFactor, minNeighbors, minSize):
# face will detected in gray image
image_gray=cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
faces=face_detection.detect(image_gray,
scaleFactor=scaleFactor,
minNeighbors=minNeighbors,
minSize=minSize)
for x, y, w, h in faces:
#detected faces shown in color image
cv2.rectangle(image,(x,y),(x+w, y+h),(127, 255,0),3)
show_image(image)
detect_face(image=img,
scaleFactor=1.9,
minNeighbors=1,
minSize=(30,30))
Loading another image
img3 = cv2.imread('people2.jpg')
show_image(img3)
detect_face(image=img3,
scaleFactor=1.9,
minNeighbors=3,
minSize=(30,30))
detect_face(image=img3,
scaleFactor=1.9,
minNeighbors=1,
minSize=(10,30))